<template>
  <view class="container">
    <!-- 加载状态 -->
    <view v-if="isLoading" class="loading-overlay">
      <view class="loading-content">
        <view class="loading-icon">
          <uni-icons type="spinner-cycle" size="30" color="#3B82F6"></uni-icons>
        </view>
        <text class="loading-text">数据加载中...</text>
      </view>
    </view>
    
    <view v-else>
      <!-- 导航栏 -->
      <view class="nav-bar">
        <view class="nav-item" :class="{ active: currentView === 'day' }" @click="switchView('day')">
          今日活动
        </view>
        <view class="nav-item" :class="{ active: currentView === 'week' }" @click="switchView('week')">
          本周统计
        </view>
      </view>

      <!-- 今日活动视图 -->
      <view v-if="currentView === 'day'" class="day-view">
        <!-- 活动概览卡片 -->
        <view class="card">
          <view class="card-header">
            <text class="title">今日活动数据</text>
            <view class="stats">
              <text class="stat-value">{{ patientData.day.steps }}</text>
              <text class="stat-label">步数</text>
            </view>
          </view>

          <!-- 活动目标进度 -->
          <view class="progress-container">
            <view class="progress-info">
              <text class="progress-label">活动目标完成度</text>
              <text class="progress-value">{{ patientData.day.progress }}%</text>
            </view>
            <view class="progress-bar">
              <view class="progress-fill" :style="{ width: patientData.day.progress + '%' }"></view>
            </view>
            <text class="progress-tip">建议每日{{ patientData.day.target }}步</text>
          </view>

          <!-- 活动数据汇总 -->
          <view class="activity-summary">
            <view class="summary-item">
              <text class="summary-value">{{ patientData.day.distance }} </text>
              <text class="summary-label">活动距离(/km)</text>
            </view>
            <view class="summary-item">
              <text class="summary-value">{{ parseFloat((patientData.day.activeMinutes/60).toFixed(1)) }}</text>
              <text class="summary-label">活动时间(/h)</text>
            </view>
          </view>
        </view>

        <!-- 活动时段分布 -->
        <view class="card">
          <view class="card-header">
            <text class="title">活动时段分布</text>
          </view>
          <qiun-data-charts 
            v-if="hourlyData && hourlyData.series[0].data.some(v => v > 0)"
            type="column" 
            :opts="columnOpts" 
            :chartData="hourlyData" 
          />
        </view>

        <!-- 医生建议卡片 -->
        <view class="card advice-card">
          <view class="card-header">
            <text class="title">康复建议</text>
          </view>
          <text class="advice-text">{{ patientData.day.advice }}</text>
        </view>
      </view>

      <!-- 本周统计视图 -->
      <view v-else class="week-view">
        <!-- 周活动趋势 -->
        <view class="card">
          <view class="card-header">
            <text class="title">本周活动趋势</text>
            <view class="stats">
              <text class="stat-value">{{ patientData.week.avgSteps }}</text>
              <text class="stat-label">日均步数</text>
            </view>
          </view>
          <qiun-data-charts 
            v-if="weekTrendData && weekTrendData.series[0].data.some(v => v > 0)"
            type="line" 
            :opts="lineOpts" 
            :chartData="weekTrendData" 
          />
        </view>
        <!-- 周活动达标情况 -->
        <view class="card">
          <view class="card-header">
            <text class="title">本周达标情况</text>
          </view>
          <view class="compliance-grid">
            <view class="compliance-day" v-for="(day, index) in patientData.week.days" :key="index"
              :class="{ complete: day.complete }">
              <text class="day-name">{{ day.name }}</text>
              <text class="day-status">{{ day.complete ? '达标' : '未达' }}</text>
            </view>
          </view>
        </view>

        <!-- 周活动汇总 -->
        <view class="card week-summary-card">
          <view class="summary-row">
            <view class="summary-col">
              <text class="summary-title">总步数</text>
              <text class="summary-main">{{ patientData.week.totalSteps }}</text>
            </view>
            <view class="summary-col">
              <text class="summary-title">达标天数</text>
              <text class="summary-main">{{ patientData.week.completeDays }}天</text>
            </view>
          </view>
          <view class="summary-row">
            <view class="summary-col">
              <text class="summary-title">最长活动</text>
              <text class="summary-main">{{ patientData.week.longestActive }}分钟</text>
            </view>
            <view class="summary-col">
              <text class="summary-title">最佳表现</text>
              <text class="summary-main">{{ patientData.week.bestDay }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useHealthData } from '../../../store/modules/useHealthData'
import { get } from '@/utils/request'
// import { uniIcons } from '@dcloudio/uni-ui'

const healthStore = useHealthData()

const USER_ID = healthStore.getCurUserId  ;

const isLoading = ref(false)
const currentView = ref('day')

const patientData = ref({
  day: {
    steps: 0,
    progress: 0,
    target: 5000,
    distance: '0',
    activeMinutes: 0,
    advice: ""
  },
  week: {
    avgSteps: 0,
    totalSteps: 0,
    completeDays: 0,
    longestActive: 0,
    bestDay: '',
    days: [
      { name: "周一", complete: false },
      { name: "周二", complete: false },
      { name: "周三", complete: false },
      { name: "周四", complete: false },
      { name: "周五", complete: false },
      { name: "周六", complete: false },
      { name: "周日", complete: false }
    ]
  }
})

const columnOpts = {
  color: ["#3B82F6"],
  padding: [15, 15, 0, 5],
  enableScroll: false,
  legend: {
    show: false
  },
  xAxis: {
    disableGrid: true,
    axisLineColor: "#E4E7ED",
    fontSize: 10,
    rotateLabel: 45, // 旋转标签
    // itemCount: 8,  // 显示所有标签
    // labelCount: 8,  // 设置最多显示的标签数量
    margin: 20,   // 增加底部间距
    boundaryGap: "justify" // 两端对齐
  },
  yAxis: {
    gridType: "dash",
    dashLength: 4,
    data: [{
      min: 0,
      axisLineColor: "#E4E7ED",
      splitLineColor: "#F7F8FA"
    }]
  },
  extra: {
    column: {
      type: "group",
      width: 15,
      categoryGap: 5,
      activeBgColor: "#000000",
      activeBgOpacity: 0.08
    }
  }
}

const lineOpts = {
  color: ["#3B82F6"],
  padding: [15, 15, 0, 5],
  enableScroll: false,
  legend: {
    show: false
  },
  xAxis: {
    disableGrid: true,
    axisLineColor: "#E4E7ED"
  },
  yAxis: {
    gridType: "dash",
    dashLength: 4,
    data: [{
      min: 0,
      axisLineColor: "#E4E7ED",
      splitLineColor: "#F7F8FA"
    }]
  },
  extra: {
    line: {
      type: "straight",
      width: 3,
      activeType: "hollow"
    }
  }
}

const hourlyData = ref({
  categories: ["6-8", "8-10", "10-12", "12-14", "14-16", "16-18", "18-20", "20-22"],
  series: [
    {
      name: "步数",
      data: [0, 0, 0, 0, 0, 0, 0, 0]
    }
  ]
})

const weekTrendData = ref({
  categories: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
  series: [
    {
      name: "步数",
      data: [0, 0, 0, 0, 0, 0, 0]
    }
  ]
})

// 加载数据
const loadData = async () => {
  try {
    isLoading.value = true
    const res = await get(
      `/activity/${USER_ID}/statistics?period=${currentView.value}`,
      'api/v1'
    )

    if (res.code === 200 && res.data) {
      if (currentView.value === 'day') {
        // 更新日视图数据
        patientData.value.day = {
          steps: res.data.steps,
          progress: res.data.progress,
          target: res.data.target,
          distance: res.data.distance,
          activeMinutes: res.data.activeMinutes,
          advice: res.data.advice
        }
        // 更新时段分布数据
        if (res.data.hourlyData) {
          hourlyData.value = res.data.hourlyData
        }
      } else {
        // 更新周视图数据
        patientData.value.week = {
          avgSteps: res.data.avgSteps,
          totalSteps: res.data.totalSteps,
          completeDays: res.data.completeDays,
          longestActive: res.data.longestActive,
          bestDay: res.data.bestDay,
          days: res.data.days
        }
        // 更新周趋势数据
        if (res.data.trendData) {
          weekTrendData.value = res.data.trendData
        }
      }
    }
  } catch (error) {
    console.error('Failed to load activity data:', error)
    uni.showToast({
      title: '数据加载失败',
      icon: 'none'
    })
  } finally {
    // 添加一个小延迟，确保数据完全准备好
    setTimeout(() => {
      isLoading.value = false
    }, 300)
  }
}

const switchView = (view) => {
  currentView.value = view
  loadData() // 切换视图时重新加载数据
}

onMounted(() => {
  loadData() // 初始化时加载数据
})

// 监听视图切换
watch(currentView, async () => {
  await loadData()
})

</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  background-color: #F7F8FA;
  min-height: 100vh;
}

/* 导航栏样式 */
.nav-bar {
  display: flex;
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);

  .nav-item {
    flex: 1;
    text-align: center;
    padding: 24rpx 0;
    font-size: 28rpx;
    color: #666;
    position: relative;
    transition: all 0.3s;

    &.active {
      color: #3B82F6;
      font-weight: 500;

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 80rpx;
        height: 4rpx;
        background-color: #3B82F6;
        border-radius: 2rpx;
      }
    }
  }
}

/* 卡片通用样式 */
.card {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  padding: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.04);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;

  .title {
    font-size: 32rpx;
    font-weight: 500;
    color: #333;
  }

  .stats {
    display: flex;
    flex-direction: column;
    align-items: flex-end;

    .stat-value {
      font-size: 28rpx;
      font-weight: 500;
      color: #3B82F6;
    }

    .stat-label {
      font-size: 24rpx;
      color: #999;
      margin-top: 4rpx;
    }
  }
}

/* 进度条样式 */
.progress-container {
  margin: 30rpx 0;

  .progress-info {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10rpx;

    .progress-label {
      font-size: 26rpx;
      color: #666;
    }

    .progress-value {
      font-size: 26rpx;
      color: #3B82F6;
      font-weight: 500;
    }
  }

  .progress-bar {
    height: 12rpx;
    background-color: #F0F0F0;
    border-radius: 6rpx;
    overflow: hidden;

    .progress-fill {
      height: 100%;
      background: linear-gradient(90deg, #3B82F6, #60A5FA);
      border-radius: 6rpx;
      transition: width 0.5s ease;
    }
  }

  .progress-tip {
    display: block;
    font-size: 24rpx;
    color: #999;
    text-align: right;
    margin-top: 8rpx;
  }
}

/* 活动数据汇总 */
.activity-summary {
  display: flex;
  justify-content: space-around;
  margin-top: 30rpx;

  .summary-item {
    text-align: center;

    .summary-value {
      font-size: 36rpx;
      font-weight: 500;
      color: #333;
      display: block;
    }

    .summary-label {
      font-size: 24rpx;
      color: #999;
    }
  }
}

/* 医生建议卡片 */
.advice-card {
  .advice-text {
    font-size: 26rpx;
    color: #666;
    line-height: 1.6;
  }
}

/* 周达标情况网格 */
.compliance-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 20rpx;
  margin-top: 20rpx;

  .compliance-day {
    text-align: center;
    padding: 16rpx 0;
    border-radius: 8rpx;
    background-color: #F7F8FA;

    &.complete {
      background-color: #EFF6FF;

      .day-status {
        color: #3B82F6;
      }
    }

    .day-name {
      font-size: 24rpx;
      color: #666;
      display: block;
    }

    .day-status {
      font-size: 24rpx;
      color: #999;
      display: block;
      margin-top: 8rpx;
    }
  }
}

/* 周活动汇总卡片 */
.week-summary-card {
  .summary-row {
    display: flex;
    margin-bottom: 20rpx;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .summary-col {
    flex: 1;

    &:first-child {
      margin-right: 20rpx;
    }

    .summary-title {
      font-size: 26rpx;
      color: #999;
      display: block;
      margin-bottom: 8rpx;
    }

    .summary-main {
      font-size: 32rpx;
      font-weight: 500;
      color: #333;
    }
  }
}

/* 图表容器 */
qiun-data-charts {
  display: block;
  width: 100%;
  height: 400rpx;
}

/* 加载状态样式 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.95);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
  
  .loading-content {
    text-align: center;
    padding: 30rpx;
    border-radius: 20rpx;
    background-color: rgba(255, 255, 255, 0.8);
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
    
    .loading-icon {
      margin-bottom: 20rpx;
      animation: rotate 1s linear infinite;
    }
    
    .loading-text {
      font-size: 28rpx;
      color: #666;
      font-weight: 500;
    }
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>